package com.mate.cloud.auth.handler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义登陆失败
 * @author:         MI
 * @email:          448341911@qq.com
 * @createTime:     2025/6/5 16:54
 * @updateUser:     MI
 * @updateTime:     2025/6/5 16:54
 * @updateRemark:   修改内容
 * @version:        1.0
 */
@Slf4j
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {


//    @Autowired
//    private ObjectMapper objectMapper;
//

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("onAuthenticationFailure 登陆失败");
        // 获取用户名（如果有）
        String username = request.getParameter("username");
        // 记录登录失败日志
        System.err.println("用户 '" + username + "' 登录失败: " + exception.getMessage());

        // 根据不同的异常类型处理登录失败
        String errorMessage = getErrorMessage(exception);
        // 将错误信息存储到session中
        request.getSession().setAttribute("errorMessage", errorMessage);

        // 重定向到登录页面
        response.sendRedirect(request.getContextPath() + "/login?error");
//        //修改状态码
//        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
//        response.setContentType("application/json;charset=utf-8");
//        response.getWriter().write(objectMapper.writeValueAsString(exception.getMessage()));

    }
    // 根据不同的异常类型返回不同的错误信息
    private String getErrorMessage(AuthenticationException exception) {
        if (exception instanceof BadCredentialsException) {
            return "用户名或密码错误";
        } else if (exception instanceof LockedException) {
            return "账户已被锁定，请联系管理员";
        } else if (exception instanceof DisabledException) {
            return "账户已被禁用，请联系管理员";
        } else if (exception instanceof AccountExpiredException) {
            return "账户已过期，请联系管理员";
        } else if (exception instanceof CredentialsExpiredException) {
            return "密码已过期，请重置密码";
        } else {
            return "登录失败，请稍后再试";
        }
    }

}
